package com.hp.order_service.controller;

import com.hp.order_service.config.WebSocketUtils;
import com.hp.order_service.service.PayService;
import com.hp.order_service.wxpay.WXPayUtil;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private PayService payService;

    private String tradeNo;

    //二维码生成
    @GetMapping("/code")
    public void qrcode(@RequestParam("goodsId")String goodsId,
                       @RequestParam("price")Long price,
                       HttpServletResponse response){
        try {
            //下单
            Map<String,String> map = payService.makeOrder(goodsId, price);
            //生成二维码
            payService.makeQRCode(map.get("code_url"),response);
            System.out.println("生成订单号：" + map.get("trade_no"));
            tradeNo = map.get("trade_no");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //支付后通知
    @PostMapping("/updateOrder")
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获得微信传来的xml字符串
        String str = Streams.asString(request.getInputStream());
        //将字符串xml转换为Map
        Map<String, String> map = WXPayUtil.xmlToMap(str);
        //读取订单号
        String no = map.get("out_trade_no");
        //模拟修改商户后台数据库订单状态
        System.out.println("更新订单状态:"+no);
        //给微信发送消息
        response.getWriter().println("<xml>\n" +
                "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                "   <appid><![CDATA["+map.get("appid")+"]]></appid>\n" +
                "   <mch_id><![CDATA["+map.get("mch_id")+"]]></mch_id>\n" +
                "   <nonce_str><![CDATA["+map.get("nonce_str")+"]]></nonce_str>\n" +
                "   <openid><![CDATA["+map.get("openid")+"]]></openid>\n" +
                "   <sign><![CDATA["+map.get("sign")+"]]></sign>\n" +
                "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                "   <prepay_id><![CDATA["+map.get("prepay_id")+"]]></prepay_id>\n" +
                "   <trade_type><![CDATA[NATIVE]]></trade_type>\n" +
                "</xml>");
        //通知前端支付成功
        WebSocketUtils.sendMessage("ok");
    }

    //检查订单状态
    @PostMapping("checkOrder")
    public String checkOrder() throws Exception {
        System.out.println("trade_no:" + tradeNo);
        if(StringUtils.isEmpty(tradeNo)){
            return null;
        }
        String success = payService.checkOrder(tradeNo);
        System.out.println("check:" + success);
        return success;
    }
}